import React, {Component} from "react";
import {Button, Col, Divider, Pagination, Row, Table, Tooltip} from "antd";
import PropTypes from 'prop-types';
import {SearchBtnContainer, SearchForColumns, SearchInput, SearchLabel} from "@/common/Table/style";
import {SearchOutlined} from '@ant-design/icons';
import Config from '@/config'
import {Btn, OtherControlBox} from "./style";
import Confirm from "@/common/Modal/Confirm";
import {StrongFontColor, SuperLightFontColor} from "@/style/Color";

/**
 * 二次封装Ant Table列表 及 Pagination分页器
 * 接受传参：
 *         rowKey    ——>  数据主键（可不传，默认为 id ）
 *         columns   ——>  列表项配置
 *         onReload  ——>  请求数据加载回调犯法
 *         defaultPage ——>  默认页数（可不传，默认为 1 ）
 *         defaultSize ——>  默认单页条数（可不传，默认为 5 ）
 */

class JTable extends Component {
    form = React.createRef();
    childForm = React.createRef();

    constructor(props) {
        super(props);
        this.handleRefresh = this.handleRefresh.bind(this);
        this.handleOnChange = this.handleOnChange.bind(this);
        this.handleClickDelete = this.handleClickDelete.bind(this);
        this.handleSearchInputChange = this.handleSearchInputChange.bind(this)
        this.handleReady2Search = this.handleReady2Search.bind(this);
        this.handleClickAdd = this.handleClickAdd.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        let {onSelect, rowKey = 'id', columns, onReload, defaultPage, defaultSize} = this.props;
        let searchColumns = [];
        columns.forEach(obj => {
            if (obj.search) {
                searchColumns.push({
                    label: obj.title,
                    key: obj.dataIndex
                })
            }
        })
        this.state = {
            onSelect,
            rowKey,
            columns,
            formData: {},
            page: defaultPage,
            size: defaultSize,
            searchColumns,
            searchParams: {},
            tableLoading: true,
            disableClick: false,
            selectedRowKeys: [],
            confirmVisible: false,
            shouldUpdate: false,
        };
        //初始化页面数据
        if (onReload) {
            onReload({page: defaultPage, size: defaultSize});
        }
    }

    /* 点击 "添加" 时，展示窗口 */
    handleClickAdd() {
        this.props.clickSaveCallback(true)
    }

    /* 取消显示 */
    handleCancel() {
        /* 重置表单数据 */
        this.form.current.resetFields()
        this.setState({
            formData: {},
            shouldUpdate: true,
            fileItems: [],
            ModalVisible: false,
            confirmVisible: false,
        });
    }

    handleClickDelete() {
        this.setState({
            confirmVisible: true
        })
    }

    /* Props更新 ——> 解除Loading */
    componentDidUpdate(prevProps) {
        if (this.state.tableLoading) {
            this.setState({tableLoading: false})
        }
    }

    /* 点击搜索时回调方法 */
    handleReady2Search() {
        let params = {
            page: this.props.defaultPage,
            size: this.props.defaultSize,
            ...this.state.searchParams
        }
        this.setState({
            ...params
        })
        this.setState({tableLoading: true})
        this.props.onReload(params);
    }

    /* 检索条件更新到STATE */
    handleSearchInputChange(searchKey, e) {
        /* 更新STATE */
        let {searchParams} = this.state;
        searchParams[searchKey] = e.target.value;
        this.setState({
            ...searchParams
        })
    }

    /* 刷新Table数据 */
    handleRefresh() {
        if (this.props.onReload) {
            let {page, size, searchParams} = this.state;
            let params = {
                page,
                size,
                ...searchParams
            }
            this.setState({tableLoading: true})
            this.props.onReload(params);
        }
    }

    /* 分页器事件 */
    handleOnChange(page, size) {
        if (this.props.onReload) {
            this.setState({page, size})
            let params = {
                page,
                size,
            }
            this.setState({tableLoading: true})
            this.props.onReload(params);
        }
    }

    render() {
        let {rowKey = 'id', columns, disableClick, selectedRowKeys} = this.state;
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys
                })
            },
        };
        return (
            <>
                {/* 多选删除弹窗 */}
                <Confirm visible={this.state.confirmVisible}
                         dataSize={this.state.selectedRowKeys.length}
                         onOk={() => {
                             this.props.onDelete({ids: this.state.selectedRowKeys})
                             this.setState({confirmVisible: false})
                         }}
                         onCancel={() => this.setState({confirmVisible: false})}
                />
                <Row gutter={[16, 16]}>
                    <Col span={24}>
                        {/* 条件检索区 */}
                        <SearchForColumns>
                            <Row gutter={[16, 16]}>
                                {
                                    this.state.searchColumns.map(
                                        (column, index) => {
                                            return <Col span={5} key={index}>
                                                <SearchLabel key={index + 'label'}>{column.label}:</SearchLabel>
                                                <SearchInput label={column.label}
                                                             key={index + 'input'}
                                                             value={this.state.searchParams[column.label]}
                                                             onChange={(e) => this.handleSearchInputChange(column.key, e)}
                                                />
                                            </Col>
                                        }
                                    )
                                }
                                {/* 条件检索 - 按钮 */}
                                <Col>
                                    <SearchBtnContainer>
                                        <Row gutter={[16, 16]}>
                                            <Col span={9}>
                                                {/* 搜索 */}
                                                <Tooltip placement="bottom" color={SuperLightFontColor} title={<span
                                                    style={{fontSize: '12px', color: StrongFontColor}}>搜索</span>}>
                                                    <Button size={"small"} type={"primary"}
                                                            onClick={this.handleReady2Search}><SearchOutlined/></Button>
                                                </Tooltip>
                                            </Col>
                                            <Col span={9}>
                                                {/* 刷新 */}
                                                <Tooltip placement="bottom" color={SuperLightFontColor} title={<span
                                                    style={{fontSize: '12px', color: StrongFontColor}}>刷新</span>}>
                                                    <Button size={"small"} onClick={this.handleRefresh}>
                                                        <Config.IconFont
                                                            type={'icon-ai244'}
                                                            style={{color: '#1890FF', fontSize: '20px'}}/>
                                                    </Button>
                                                </Tooltip>
                                            </Col>
                                            <Col span={6}/>
                                        </Row>
                                    </SearchBtnContainer>
                                </Col>
                            </Row>
                        </SearchForColumns>
                    </Col>
                    <Col span={24}>
                        <Divider style={{margin: '0 0 15px 0'}}/>
                        {/* 数据操作区 */}
                        <OtherControlBox>
                            <Btn className={`${disableClick ? 'disable' : ''}`}
                                 onClick={() => !disableClick ? this.handleClickAdd() : null}>
                                添加
                            </Btn>
                            <Btn className={`del ${selectedRowKeys.length === 0 ? 'disable' : ''}`}
                                 onClick={() => selectedRowKeys.length !== 0 ? this.handleClickDelete() : null}>
                                删除
                            </Btn>
                        </OtherControlBox>
                        {/* Table表格 */}
                        <Table
                            rowSelection={{
                                ...rowSelection
                            }}
                            bordered={true}
                            rowKey={rowKey}
                            style={{float: 'left', width: '100%'}}
                            columns={columns}
                            dataSource={this.props.data.rows}
                            size={'small'}
                            loading={this.state.tableLoading}
                            scroll={{x: 1000}}
                            pagination={false}
                        />
                    </Col>
                    <Col span={24}>
                        {/* 分页器 */}
                        <Pagination
                            style={{textAlign: 'center'}}
                            defaultCurrent={1}
                            defaultPageSize={10}
                            pageSize={this.state.size}
                            current={this.state.page}
                            size="small"
                            showQuickJumper
                            total={this.props.data.total}
                            showTotal={(total) => {
                                `共计${total}条数据`
                            }}
                            onChange={this.handleOnChange}
                        />
                    </Col>
                </Row>
            </>
        )
    }
}

/**
 * 定义、声明Props属性
 */
JTable.propTypes = {
    /* 数据主键（非必要，默认值："id"） */
    rowKey: PropTypes.string,
    /* 列表项配置（必要） */
    columns: PropTypes.array,
    /* 请求数据加载回调方法（必要） */
    onReload: PropTypes.func,
    /* 请求删除数据回调方法（必要） */
    onDelete: PropTypes.func,
    /* 默认页数（非必要，默认值：1） */
    defaultPage: PropTypes.number,
    /* 默认单页条数（非必要，默认值：5） */
    defaultSize: PropTypes.number,
    /* 数据源（必要） */
    data: PropTypes.array,
    /* 用来感知用户在组件内部点击了新增按钮（必要） */
    clickSaveCallback: PropTypes.func,
}

/**
 * Props属性默认值
 */
JTable.defaultProps = {
    rowKey: 'id',
    defaultPage: 1,
    defaultSize: 5,
}
export default JTable;
